
import $baseUrl from "@/config/index.js"
const BASE_URL = $baseUrl.baseUrl + 'api/'
  // "https://forum.chunchuangkeji.cn/api/" //  接口域名
const getToken = () => {
  return uni.getStorageSync('token') || '';
};


export const request = ({url, method, data = {},contentType}) => {
	console.log(url,"url",getToken());
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method: method,
      data: data,
      header: {
        'content-type':contentType || 'application/json',
       'token': `${getToken()}`, // 添加 token 到请求头
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // token 失效，跳转登录页
		  let content = ''
			if(getToken()){
				content ='身份验证失效，请重新登录'
			}else{
				content ='您未登录，请先登录'
			}
            uni.showModal({
            	confirmText:'登录',
				title:'提示',
				content,
				showCancel:true,
				success(e){
					if(e.confirm){
						 uni.navigateTo({ url: '/pages/login/login' });
					}
				}
            })
          // uni.showToast({ title: '身份验证失效，请重新登录', icon: 'none' });
          // uni.navigateTo({ url: '/pages/login/login' }); // 跳转到登录页
          reject(new Error('Token 失效'));
        } else {
          uni.showToast({ title: '请求失败', icon: 'none' });
          reject(new Error(`请求出错：${res.errMsg}`));
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络异常', icon: 'none' });
        reject(err);
      },
    });
  });
};

 